#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :mongodb.py
# @Time      :2024/10/19 20:30
# @Author    :zhou_yi

""" 常用查询
$lt小于{'age': {'$lt': 20}}
$gt大于{'age': {'$gt': 20}}
$lte小于等于{'age': {'$lte': 20}}
$gte大于等于{'age': {'$gte': 20}}
$ne不等于{'age': {'$ne': 20}}
$in在范围内{'age': {'$in': [20, 23]}}
$nin不在范围内{'age': {'$nin': [20, 23]}}

$regex匹配正则{'name': {'$regex': '^M.*'}}name以M开头
$exists属性是否存在{'name': {'$exists': True}}name属性存在
$type类型判断{'age': {'$type': 'int'}}age的类型为int
$mod数字模操作{'age': {'$mod': [5, 0]}}年龄模5余0
$text文本查询{'$text': {'$search': 'Mike'}}text类型的属性中包含Mike字符串
$where高级条件查询{'$where': 'obj.fans_count == obj.follows_count'}自身粉丝数等于关注数


"""

from datetime import datetime
from pymongo import MongoClient


class MongoDB:
    def __init__(self, dbname='work'):
        self.conn = MongoClient(host='49.232.233.253', port=27017)
        self.db = self.conn[dbname]

    # 查集合所有数据
    def collection_all(self, collection_name) -> list[dict]:
        _cursor = self.db[collection_name].find()
        return list(_cursor)

    # 求集合中文档id号的最大值 并生成新值
    def collection_max_id_and_new_id(self, collection_name, spl='-') -> tuple:
        """
            求 集合中 id 最大值,并生成 新增值id 适合 id=p-0016
            在表单新增数据的时候 按规则 自动分配给一个id值
        :param collection_name:
        :param spl: 字母与数字的分割符
        :return: p-0016（原数据中最大的） , p-0017（新）
        """
        _cursor = self.db[collection_name].find({}, {'id': 1})  # id号
        _ids = list(_cursor)
        flex_id = _ids[0]['_id'].split(spl)[0]  # 取前缀 "p"
        id_lst = [itm['_id'].split(spl)[1] for itm in _ids]  # 取数字部分 "0016"
        max_id = sorted(id_lst)[-1]  # 排序
        current_id = f"{int(max_id) + 1 :0>4}"
        return f"{flex_id}-{max_id}", f"{flex_id}-{current_id}"

    # 数据库中添加数据
    def insert_one(self, collection_name, new_data: dict):
        collection = self.db[collection_name]
        collection.insert_one(new_data)

    # 数据库中添加多条数据
    def insert_many(self, collection_name, new_data_lst: list[dict]):
        collection = self.db[collection_name]
        collection.insert_many(new_data_lst)

    # 公司名 查询 公司
    def company_data_by_name(self, name) -> dict:
        """
            从company 表中查找 公司名称 唯一值
        :param name: 公司名称
        :return:
        """
        query = {"name": f"{name}"}
        document = self.db.company.find_one(query)
        return document

    # 正则 查询 公司
    def company_data_by_relation(self, *relation, is_id=False) -> list:
        pattern = ".*"
        for itm in relation:
            pattern = pattern + itm + '.*'
        query = {"relation": {"$regex": pattern}}
        if is_id:
            cursor = self.db.company.find(query)
        else:
            cursor = self.db.company.find(query, {'_id': 0})
        return list(cursor)

    # 从address集合中查找point数据
    def address_data_by_point(self, point: str) -> dict:
        return self.db.address.find_one({'point': point})

    def address_data_by_customID(self, customID: str) -> list:
        cursor = self.db.address.find({'customID': customID})
        return list(cursor)

    # 从clear_waster_records查找fk数据
    def clear_waster_records_by_fk(self, fk: str) -> list:
        return list(self.db.clear_waster_records.find({'fk': fk}))

    # 从clear_waster_records查找 时间范围的数据
    def clear_waster_records_by_fk_and_date(self, fk, start, end) -> list:
        query = {'fk': fk,
                 'datetime': {
                     "$gte": start,
                     "$lte": end
                 }}
        _ = list(self.db.clear_waster_records.find(query))
        return _


if __name__ == '__main__':
    # print(three_data_by_name(name="添加"))
    #
    # r = company_data_by_name(name="北京宏鑫汇能循环经济发展科技有限公司")
    # print(type(r))

    m = MongoDB()
    print(m.company_data_by_name("北京市顺义区旺泉街道办事处"))

    # print(m.address_data_by_point('望泉西里一区'))

    # print(m.clear_waster_records_by_fk(fk='p-2006'))
    #
    # dt1 = datetime.strptime('2024-11-1', "%Y-%m-%d")
    # dt2 = datetime.strptime('2025-01-09', "%Y-%m-%d")
    # for i in m.clear_waster_records_by_fk_and_date('p-2006', dt1, dt2):
    #     print(i)
    # rs = m.company_data_by_name('北京宏鑫汇能循环经济发展科技有限公司')

    # for i in m.company_data_by_relation('租'):
    #     print(i)
    # new_ = {
    #     "fk": "p-1002",
    #     "datatime": datetime.datetime.now(),
    #     "f_pic": [
    #         "图片1",
    #         "图片2"
    #     ],
    #     "b_pic": [
    #         "图片1",
    #         "图片2"
    #     ],
    #     "w_total": 200,
    #     "w1": 20,
    #     "w2": 10,
    #     "w3": 11,
    #     "w4": 13,
    #     "w5": 16,
    #     "w6": 16,
    #     "w7": 16,
    #     "w8": 11
    # }
    # m.insert_one('clear_waster_records', new_)
    # print('finish')

    ...
